package com.efounder.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import com.efounder.bean.Address;
import com.efounder.bean.CartItem;
import com.efounder.bean.UpdateOrderBadgeEvent;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.http.EFHttpRequest;
import com.efounder.mobilemall.R;
import com.efounder.util.ToastUtil;
import com.efounder.utils.MallRequestUtil;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;

import static com.efounder.utils.MallRequestUtil.ADDRESS_LIST_URL;
import static com.efounder.utils.MallRequestUtil.ORDER_CREATE_URL;

/**
 * @deprecated 使用新的CreateOrderActivity
 * Created by will on 18-2-8.
 * 确认订单的activity，上部透明
 */

public class MallSubmitActivity extends Activity implements View.OnClickListener{

    private String TAG = this.getClass().getSimpleName();

    private List<Address> addresses;
    private List<CartItem> checkItems;
    private Address defaultAddress;
    private Address targetAddress = null;
    private TextView tvAddress;
    private double allPrice;
    private double allTax;
    private String orderTitle = "";
    private static final int CHOOSE_ADDRESS_REQUEST_CODE = 8801;
    private static final int ADD_ADDRESS_REQUEST_CODE = 8802;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_submit_order);
        Bundle bundle = getIntent().getExtras();
        addresses = (List<Address>)bundle.get("address");
        defaultAddress = (Address) bundle.get("defaultAddress");
        allPrice = bundle.getDouble("allPrice");
        allTax = bundle.getDouble("allTax");
        checkItems = (List<CartItem>) bundle.get("checkItems");
        initView();
    }

    public void initView() {
        View transparentView = (View) findViewById(R.id.transparent_view);
        transparentView.setOnClickListener(this);
        tvAddress = (TextView) findViewById(R.id.tv_address);
        tvAddress.setOnClickListener(this);
        TextView tvTotalPrice = (TextView) findViewById(R.id.tv_total_price);
        TextView tvSubmit = (TextView) findViewById(R.id.tv_submit);
        tvSubmit.setOnClickListener(this);
        tvTotalPrice.setText("￥" + (allPrice+allTax));
        initAddress(null);
    }

    private void initAddress(String addressId) {
        if (addresses.size() > 0) {
            for (Address address : addresses) {
                if (address.isCurrentSelected()) {
                    tvAddress.setText(address.getUserName() + "，" + address.getAddress());
                    targetAddress = address;
                }
            }
            if (addressId != null) {
                for (Address address : addresses) {
                    if (address.getAddressId().equals(addressId)) {
                        tvAddress.setText(address.getUserName() + "，" + address.getAddress());
                        targetAddress = address;
                    }
                }
            }
            if (targetAddress == null) {
                if (defaultAddress != null) {
                    tvAddress.setText(defaultAddress.getUserName() + "，" + defaultAddress.getAddress());
                } else {
                    tvAddress.setText(addresses.get(0).getUserName() + "，" + addresses.get(0).getAddress());
                }
            }
        }
    }

    @Override
    public void finish() {
        super.finish();
        this.overridePendingTransition(R.anim.bottom_dialog_exit,0);
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.tv_submit) {
            //请求生成订单
            HashMap<String, String> map = new HashMap<>();
                if (targetAddress!=null) {
                    map.put("addressId", targetAddress.getAddressId());
                }else if (defaultAddress!=null){
                    map.put("addressId", defaultAddress.getAddressId());
                }else if (addresses.size()>0) {
                    map.put("addressId", addresses.get(0).getAddressId());
                }else {
                    ToastUtil.showToast(this, R.string.mail_fill_correct_address);
                    return;
                }
                map.put("userId", EnvironmentVariable.getUserName());
                try {
                    JSONArray jsonArray = new JSONArray();
                    for (CartItem cartItem : checkItems) {
                        JSONObject jsonObject1 = new JSONObject();
                        jsonObject1.put("goodbh", cartItem.getItemId());
                        jsonObject1.put("goodNum", cartItem.getQuantity());
                        jsonObject1.put("goodPrice", cartItem.getPrice());
                        orderTitle = orderTitle.concat(cartItem.getName()+" ");
                        jsonArray.put(jsonObject1);
                    }
                    map.put("goods", jsonArray.toString());
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                MallRequestUtil.getRequest(TAG, ORDER_CREATE_URL, map, new MallRequestUtil.MallRequestCallback() {
                    @Override
                    public void onSuccess(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            if ("success".equals(jsonObject.getString("result"))) {
                                ToastUtil.showToast(MallSubmitActivity.this, R.string.mail_order_submit);
                                //跳支付
                                Intent intent = new Intent(MallSubmitActivity.this, SelectionPayActivity.class);
                                intent.putExtra("orderId", jsonObject.getString("orderId"));
                                intent.putExtra("orderAmount", allPrice + allTax+"");
                                intent.putExtra("orderTitle", orderTitle);
                                startActivity(intent);
                                finish();
                            }else {
                                ToastUtil.showToast(MallSubmitActivity.this, jsonObject.getString("msg"));
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        EventBus.getDefault().post(new UpdateOrderBadgeEvent());
                    }

                    @Override
                    public void onFail(String error) {
                        //todo
                    }
                });

        } else if (id == R.id.tv_address) {
            if (addresses.size() > 0){
                Intent intent = new Intent(this, MallShowAddressActivity.class);
                intent.putExtra("address", (Serializable) addresses);
                startActivityForResult(intent, CHOOSE_ADDRESS_REQUEST_CODE);
            }else {
                Intent intent = new Intent(this, MallAddAddressActivity.class);
                startActivityForResult(intent, ADD_ADDRESS_REQUEST_CODE);
            }
        } else if (id == R.id.transparent_view) {
            finish();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case CHOOSE_ADDRESS_REQUEST_CODE:
                if (resultCode == RESULT_OK) {
                    if (data.getExtras().getString("addressId") == null) {
                        addresses = (List<Address>) data.getExtras().getSerializable("addresses");
                        initAddress(null);
                    }else {
                        String addressId = (String) data.getExtras().getString("addressId");
                        getAddress(addressId);
                    }

                }
                break;
            case ADD_ADDRESS_REQUEST_CODE:
                if (resultCode == RESULT_OK) {
                    String addressId = (String) data.getExtras().getString("addressId");
                    getAddress(addressId);
                }
                break;
        }
    }

    public void getAddress(final String addressId) {
        HashMap<String, String> map = new HashMap<>();
        map.put("userId", EnvironmentVariable.getUserName());
        MallRequestUtil.getRequest(TAG, ADDRESS_LIST_URL, map, new MallRequestUtil.MallRequestCallback() {
            @Override
            public void onSuccess(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    JSONArray jsonArray = jsonObject.getJSONArray("addresses");
                    if (jsonArray.length() > 0) {
                        addresses.clear();
                        for (int i = 0; i < jsonArray.length(); i++) {
                            JSONObject addressObject = jsonArray.getJSONObject(i);
                            Address address = new Address();
                            address.setAddressId(addressObject.getString("addressId"));
                            address.setAddress(addressObject.getString("address"));
                            address.setArea(addressObject.getString("area"));
                            address.setIsSelected(addressObject.getInt("isSelected")+"");
                            address.setUserName(addressObject.getString("userName"));
                            address.setPhone(addressObject.getString("phone"));
                            if (address.getIsSelected().equals("1")) {
                                defaultAddress = address;
                            }
                            addresses.add(address);
                        }
                        initAddress(addressId);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFail(String error) {

            }
        });
    }

    @Override
    protected void onStop() {
        super.onStop();
        EFHttpRequest.cancelRequest(TAG);
    }
}
